package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"log"
	"net/http"
	"strconv"

	//"sort"
	"time"
)

type DnfType struct {
	DnfTypeId int `xorm:"pk autoincr"`
	DnfList []*DaysNotFollowed `xorm:"-"`
}

type DaysNotFollowed struct{
	Id int `xorm:"pk autoincr"`
	Day int
	TotalCustomers int64 `xorm:"-"`
	DnfTypeId int
}

type CustomerTransactionFollow struct {
	Id int32 `xorm:"pk autoincr"`
	Name string
	Remarks string
	AccountBalance int32
	ConsultantID int32
	AddTime time.Time
	LastMessageTime time.Time
}

var x *xorm.Engine

func init() {
	var xErr error
	x, xErr = xorm.NewEngine("mysql", "root:new_password@tcp(127.0.0.1:3306)/statistics?charset=utf8")
	if xErr != nil {
		log.Fatal("数据库连接失败:", xErr)
	}
	if err := x.Sync(new(DnfType), new(DaysNotFollowed), new(CustomerTransactionFollow)); err != nil {
		log.Fatal("数据表同步失败:", err)
	}
}

func BubbleSort(arr []*DaysNotFollowed) []*DaysNotFollowed{
	for i := 0; i < len(arr)-1; i++ {
		for j := 0; j < len(arr)-i-1; j++ {
			if arr[j].Day > arr[j+1].Day {
				arr[j], arr[j+1] = arr[j+1], arr[j]
			}
		}
	}
	fmt.Println(arr)
	return arr
}

func QueryDaysNotFollowed(c *gin.Context) {

	dnfTypeId, _ := strconv.Atoi(c.PostForm("dnfTypeId"))
	var dt DnfType
	dt.DnfTypeId = dnfTypeId
	x.Where("dnf_type_id = ?", dnfTypeId).Find(&dt.DnfList)

	dt.DnfList = BubbleSort(dt.DnfList)

	fmt.Println("index：", len(dt.DnfList) - 1)
	for index, dnf := range dt.DnfList{
		if index ==  len(dt.DnfList) - 1{
			fmt.Println(index)
			total, err := x.Where("add_time <= ?", time.Now().AddDate(0,0,-dnf.Day).Format("2006-01-02 15:04:05")).Count(new(CustomerTransactionFollow))
			if err != nil{
				c.JSON(http.StatusOK, gin.H{
					"code": 500,
					"data":nil,
					"msg": err,
				})
			}
			dnf.TotalCustomers = total
			fmt.Println(dnf)

		}else {
			fmt.Println(index)
			total, err := x.Where("add_time <= ?", time.Now().AddDate(0,0,-dnf.Day).Format("2006-01-02 15:04:05")).And("add_time > ?", time.Now().AddDate(0,0,-dt.DnfList[index+1].Day).Format("2006-01-02 15:04:05")).Count(new(CustomerTransactionFollow))
			if err != nil{
				c.JSON(http.StatusOK, gin.H{
					"code": 500,
					"data":nil,
					"msg": err,
				})
				return
			}
			dnf.TotalCustomers = total
			fmt.Println(dnf)
		}
	}

	fmt.Println(dt)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data":dt,
		"msg": "成功",
	})

}

func main(){
	router := gin.Default()
	router.POST("/queryDaysNotFollowed", QueryDaysNotFollowed)
	router.Run(":8436")
}
